/*
 * Copyright (C) 2010 Peter Schönhofen
 *
 * This file is part of the Akkad Compiler Framework.
 *
 * The Akkad Compiler Framework is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

package hu.anaxo.akkad.processor.pl0

import hu.anaxo.akkad.processor.{CustomLexer, Token}
import java.util.regex.Pattern

/**
 * PL/0 lexer
 */

object PL0Lexer extends CustomLexer {

  // reserved words

  private val reserved =
      Set("BEGIN", "CALL", "CONST", "DO", "END", "IF", "ODD", "PROCEDURE", "THEN", "VAR", "WHILE")

  // symbols

  private val symbols =
      List(":=", "<=", ">=", "<>", "+", "-", "*", "/", "=", "<", ">", ",", ";", ".", "(", ")")

  /**
   * Convert name to keyword or identifier
   *
   * @param name name
   *
   * @return keyword or identifier
   */

  private def convertName(name: String): Token =
    if (reserved.contains(name))
      Keyword(name)
    else
      Identifier(name)

  // lexer rules

  override protected def token: Parser[Token] =
    regexpElem("name", "[A-Z]+".r) ^^
      { convertName(_) } |
    regexpElem("number", "[0-9]+".r) ^^
      { (value) => Number(value.toInt) } |
    regexpElem("symbol", symbols.map(Pattern.quote).mkString("|").r) ^^
      { Symbol(_) }
}
